package com.hzaupj.znz.widgets;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
import com.hzaupj.znz.R;
import com.hzaupj.znz.util.FileUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * 抓取头像的dialog 提示 使用该对话框时候 请注意当前act的 requestCode 是否与 该对话框的requestCode 重复 否则 对话框功能不能完成 引用该对话框的act 重载onActivityResult 必须调用 super.onActivityResult()
 * 
 * @author david
 */
public class PicturePicker extends DialogFragment {

	public static final String TAG = PicturePicker.class.getName();

	/** 请求相册 */
	public static final int TAKE_PICTURE_GALARY = 0x999;
	/** 请求相机 */
	public static final int TAKE_PICTURE_CAMERA = 0x998;
	/** 请求裁剪 */
	public static final int TAKE_PICTURE_CROP = 0x997;

	// private static final String DefaultImageFormate = Bitmap.CompressFormat.JPEG.toString();

	private int aspectX = 1;
	private int aspectY = 1;
	private int outputX = 80;

	private boolean doCrop = true;
	private int outputY = 80;

	private OnPictureFetchedListener listener;

	// float dipRate;

	/**
	 * 获取图片抓取
	 * 
	 * @return
	 */
	public static PicturePicker newPictureInstance(Context context) {

		return newPictureInstance(context, true);

	}

	/**
	 * 获取图片抓取
	 * 
	 * @return
	 */
	public static PicturePicker newPictureInstance(Context context, boolean doCrop) {

		return newPictureInstance(context, doCrop, -1, -1, null);

	}

	/**
	 * 配置图片抓取
	 * 
	 * @param context
	 * @param doCrop 是否进行手动裁剪
	 * @param defaultWidth 不手动裁剪时 默认宽度 -1 则采用系统界面宽度
	 * @param defaultHeight 不手动裁剪时 默认高度 -1 则采用系统界面高度
	 * @return
	 */
	public static PicturePicker newPictureInstance(Context context, boolean doCrop, int defaultWidth, int defaultHeight) {

		return newPictureInstance(context, doCrop, defaultWidth, defaultHeight, null);

	}

	/**
	 * 配置图片抓取
	 * 
	 * @param context
	 * @param doCrop 是否进行手动裁剪
	 * @param defaultWidth 不手动裁剪时 默认宽度 -1 则采用系统界面宽度
	 * @param defaultHeight 不手动裁剪时 默认高度 -1 则采用系统界面高度
	 * @return
	 */
	public static PicturePicker newPictureInstance(Context context, boolean doCrop, int defaultWidth, int defaultHeight, OnPictureFetchedListener listener) {

		PicturePicker dialog = new PicturePicker();
		dialog.aspectX = 0;
		dialog.aspectY = 0;

		dialog.doCrop = doCrop;

		if (defaultWidth == -1 || defaultHeight == -1) {
			DisplayMetrics dm = context.getApplicationContext().getResources().getDisplayMetrics();
			dialog.outputX = dm.widthPixels;
			dialog.outputY = dm.heightPixels;

		} else {
			dialog.outputX = defaultWidth;
			dialog.outputY = defaultHeight;
		}

		dialog.listener = listener;
		return dialog;

	}

	/**
	 * 获取头像抓取实例
	 * 
	 * @return
	 */
	public static PicturePicker newPhotoInstance(Context context) {

		return newPhotoInstance(context, null);

	}

	/**
	 * 获取头像抓取实例
	 * 
	 * @return
	 */
	public static PicturePicker newPhotoInstance(Context context, OnPictureFetchedListener listener) {

		PicturePicker dialog = new PicturePicker();

		dialog.aspectX = 10;
		dialog.aspectY = 10;

		dialog.outputX = 300;
		dialog.outputY = 300;
		dialog.listener = listener;
		// DisplayMetrics dm = context.getApplicationContext().getResources().getDisplayMetrics();

		return dialog;

	}

	public static class Builder {
		int outputX;
		int outputY;
		int aspectX;
		int aspectY;
		String pictureFormate;

		Uri imageUri;
		Uri sourceUri;

		public Builder(Context context) {

		}

		public Builder(int width, int height, Uri resultUri) {

		}

		public void setOutputX(int width) {
		}

		public void setOutputY(int height) {
		}

		public void setAspectX(int aspectX) {
		}

		public void setAspectY(int aspectY) {
		}

		public void setSourceImage(Uri imageUri) {
			this.imageUri = imageUri;

		}

		public Intent getIntent(Context context) {

			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(sourceUri, "image/*");
			intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
			intent.putExtra("crop", "true");
			intent.putExtra("scaleUpIfNeeded", true);
			intent.putExtra("aspectX", aspectX);// 裁剪框比例
			intent.putExtra("aspectY", aspectY);
			intent.putExtra("max-width", outputX);// 输出图片大小
			intent.putExtra("max-height", outputY);
			// intent.putExtra("outputFormat", DefaultImageFormate);

			return intent;

		}

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setStyle(Window.FEATURE_NO_TITLE, R.style.com_eu_dialogs_framentDialog);

		if (listener == null && getActivity() instanceof OnPictureFetchedListener) {
			listener = (OnPictureFetchedListener) getActivity();

		}
		// 判断是否挂载了SD卡
		String storageState = Environment.getExternalStorageState();
		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			File savedir = FileUtils.getStoreFile(getActivity());
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
		} else {
			Toast.makeText(getActivity(), "无法保存上传的头像，请检查SD卡是否挂载", Toast.LENGTH_LONG).show();
			dismiss();
		}

		// 输出裁剪的临时文件
		String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime());
		// 照片命名
		String origFileName = "sd2_" + timeStamp + ".jpg";
		String cropFileName = "sd2_crop_" + timeStamp + ".jpg";

		// 裁剪头像的绝对路径
		String protraitPath = FileUtils.getStoreFilePath(getActivity()) + "/"+cropFileName;
		File protraitFile = new File(protraitPath);

		origUri = Uri.fromFile(new File(FileUtils.getStoreFilePath(getActivity()), origFileName));
		cropUri = Uri.fromFile(protraitFile);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		View dialog = inflater.inflate(R.layout.com_eu_dialogs_picture_picker, null);
		// 设置显示位置 - 底部
		getDialog().getWindow().setGravity(Gravity.BOTTOM);

		TextView camera = (TextView) dialog.findViewById(R.id.com_eu_dialogs_btn_dlg_camera);
		TextView photoLib = (TextView) dialog.findViewById(R.id.com_eu_dialogs_btn_dlg_photoLib);

		camera.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActionCamera(origUri);
			}
		});

		photoLib.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActionPick(origUri);

			}
		});
		return dialog;

	}

	private void startActionPick(Uri resultUri) {

		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("image/*");
		intent.putExtra("return-data", false);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, resultUri);
		// intent.putExtra("outputFormat", DefaultImageFormate);

		startActivityForResult(Intent.createChooser(intent, "选择图片"), TAKE_PICTURE_GALARY);
	}

	private void startActionCamera(Uri resultUri) {

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, resultUri);
		intent.putExtra("return-data", false);
		// intent.putExtra("outputFormat", DefaultImageFormate);
		startActivityForResult(intent, TAKE_PICTURE_CAMERA);

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d(TAG, "onActivityResult----resultCode:" + resultCode + ", data:" + (data != null ? data.getData() : "data==null"));

		if (resultCode != Activity.RESULT_OK) {
			return;
		}

		switch (requestCode) {
		case TAKE_PICTURE_GALARY: // 图库图片返回
			if (data != null && data.getData() != null) {
				startActionCrop(data.getData(), cropUri);
			} else {
				startActionCrop(origUri, cropUri);
			}
			break;
		case TAKE_PICTURE_CAMERA: // 拍照返回

		// 先检查图片大小 如果图片小于预定大小 无需剪切
		{
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			try {
				BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(origUri), null, options);

				if (options.outWidth < outputX && options.outHeight < outputY) {
					cropUri = origUri;

					returnData(cropUri);

				} else {

					startActionCrop(origUri, cropUri);

				}
			} catch (FileNotFoundException e) {
				Toast.makeText(getActivity(), "图片解析失败， 请重试", Toast.LENGTH_LONG).show();

				e.printStackTrace();
			}
		}

			break;

		case TAKE_PICTURE_CROP:

			returnData(cropUri);

			break;

		}

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.support.v4.app.DialogFragment#onDismiss(android.content.DialogInterface)
	 */
	@Override
	public void onDismiss(DialogInterface dialog) {
		Log.d("onDismiss", "onDismiss");

		super.onDismiss(dialog);

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.support.v4.app.Fragment#onDestroy()
	 */
	@Override
	public void onDestroy() {
		Log.d("onDestroy", "onDestroy");

		super.onDestroy();
	}

	/**
	 * 拍照后裁剪
	 *
	 * @param data 原始图片
	 * @param output 裁剪后图片
	 */
	private void startActionCrop(Uri data, Uri output) {

		if (!doCrop) {// 不执行剪切 直接压缩
			try {
				// this.getActivity().getContentResolver().

				createImageThumbnail(getActivity(), data, output, (int) Math.max(outputX, outputY), 80);
				returnData(output);
				return;

			} catch (Throwable t) {
				t.printStackTrace();

			}
		}
		// drop==true or 压缩出现异常
		// 执行默认剪切
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(data, "image/*");
		intent.putExtra(MediaStore.EXTRA_OUTPUT, output);
		intent.putExtra("crop", "true");
		intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra("noFaceDetection", true);
		intent.putExtra("aspectX", aspectX);// 裁剪框比例
		intent.putExtra("aspectY", aspectY);
		intent.putExtra("max-width", outputX);// 输出图片大小
		intent.putExtra("max-height", outputY);
		// intent.putExtra("outputFormat", DefaultImageFormate);
		startActivityForResult(intent, TAKE_PICTURE_CROP);

	}

	/**
	 * 返回数据
	 *
	 * @param uri
	 */
	private void returnData(Uri uri) {
		if (listener != null) {
			listener.onPictureFetched(uri);
		}
		dismiss();

	}

	/**
	 * 当图片获取后的接口
	 *
	 * @author david
	 */
	public interface OnPictureFetchedListener {

		public void onPictureFetched(Uri uri);
	}

	private Uri origUri;
	private Uri cropUri;

	/**
	 * 创建缩略图
	 *
	 * @param context
	 * @param source 原始大图路径
	 * @param result 输出缩略图路径
	 * @param square_size 输出图片宽度
	 * @param quality 输出图片质量
	 * @throws java.io.IOException
	 */
	public static void createImageThumbnail(Context context, Uri source, Uri result, int square_size, int quality) throws IOException {
		Bitmap cur_bitmap = null;// 原始图片bitmap

		try {
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true; // 这个参数定义 bm为null 仅仅计算图片宽高 而不实际生成图片，提升性能避免造成内存溢出
			InputStream is = context.getContentResolver().openInputStream(source);
			cur_bitmap = BitmapFactory.decodeStream(is, null, options);
			is.close();

			int width = options.outWidth;
			int height = options.outHeight;
			Log.i("orignal imageSize", "imageSize： =width:" + width + "," + "height:" + height);
			int be = 1; // 压缩比例
			if (width > square_size || height > square_size) {
				be = Math.max(width, height) / square_size;
			}
			options.inJustDecodeBounds = false;// 设置为false 实际生产图片
			if (be > 1) {// 如果大于1 就设置压缩参数
				options.inSampleSize = be; // sampleSize 可接受任意值当时小于或者等于这个值的2次方数才会生效
			}
			is = context.getContentResolver().openInputStream(source);
			cur_bitmap = BitmapFactory.decodeStream(is, null, options);// 按压缩比较重新读取图片
			is.close();
		} catch (OutOfMemoryError e) {
			Log.e("图片处理", "source=" + source + "| OutOfMemoryError:" + e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
			Log.e("图片处理", "thumbfilePath=" + result + "|Exception:" + e.getMessage());
			e.printStackTrace();
		} finally {

		}

		if (cur_bitmap == null)
			return;

		// 原始图片的高宽
		int[] cur_img_size = new int[] { cur_bitmap.getWidth(), cur_bitmap.getHeight() };
		Log.i("cur_img_size", "cur_img_size--width:" + cur_img_size[0] + ",height:" + cur_img_size[1]);
		// 计算原始图片缩放后的宽高
		int[] new_img_size = scaleImageSize(cur_img_size, square_size);
		Log.i("new_img_size", "new_img_size--width:" + new_img_size[0] + ",height:" + new_img_size[1]);
		// 生成缩放后的bitmap
		Bitmap thb_bitmap = zoomBitmap(cur_bitmap, new_img_size[0], new_img_size[1]);
		// 生成压缩文件
		OutputStream os = context.getContentResolver().openOutputStream(result);
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		cur_bitmap.compress(CompressFormat.JPEG, quality, stream);
		byte[] bytes = stream.toByteArray();
		os.write(bytes);
		os.close();

		// // 生成缩放后的图片文件
		// saveImageToSD(thumbfilePath, thb_bitmap, quality);
		if (!cur_bitmap.isRecycled()) {
			cur_bitmap.recycle(); // 回收图片所占的内存
		}
		if (!thb_bitmap.isRecycled()) {
			thb_bitmap.recycle(); // 回收图片所占的内存
		}

	}

	/**
	 * 计算缩放图片的宽高
	 * 
	 * @param img_size
	 * @param square_size
	 * @return
	 */
	public static int[] scaleImageSize(int[] img_size, int square_size) {
		if (img_size[0] <= square_size && img_size[1] <= square_size)
			return img_size;
		double ratio = square_size / (double) Math.max(img_size[0], img_size[1]);
		return new int[] { (int) (img_size[0] * ratio), (int) (img_size[1] * ratio) };
	}

	/**
	 * 放大缩小图片
	 * 
	 * @param bitmap
	 * @param w
	 * @param h
	 * @return
	 */
	public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
		Bitmap newbmp = null;
		if (bitmap != null) {
			int width = bitmap.getWidth();
			int height = bitmap.getHeight();
			Matrix matrix = new Matrix();
			float scaleWidht = ((float) w / width);
			float scaleHeight = ((float) h / height);
			matrix.postScale(scaleWidht, scaleHeight);
			newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
		}
		return newbmp;
	}
}
